<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Kalnoy\Nestedset\NodeTrait;
use Illuminate\Support\Facades\DB;


class Team extends Model
{
    use NodeTrait;
    protected  $table='team';

    protected function getScopeAttributes()
    {
        return [ 'org_id' ];
    }

    protected $fillable = [
        'user_id',
        'name',
        'type',
        'service_target',
        'logo',
        'slogan',
        'photo',
        'org_id',
        'identifier',
        'contact_name',
        'contact_phone',
        'contact_email',
        'province_id',
        'province_name',
        'city_id',
        'city_name',
        'county_id',
        'county_name',
        'addr',
        'legal_person',
        'legal_person_id',
        'legal_person_phone',
        'certificate_photo',
        'team_photo',
        'abstract',
        'reward_time',
        'team_size',
        'auth_create_team',
        'auth_exempt_project',
        'auth_create_goods',
        'parent_id',
        'in_blacklist',
        'black_reason',
        'blacked_at',
        'join_type',
        'verify_status',
        'verify_msg',
        'address',
        'stars',
    ];

    protected $appends = array('address');

    protected $casts = [
        'certificate_photo' => 'array',
        'team_photo' => 'array',
    ];

    public function getCertificatePhotoAttribute() {
        if (isset($this->attributes['certificate_photo'])) {
            try {
                $this->attributes['certificate_photo'] = json_decode($this->attributes['certificate_photo']);
            }catch (\Exception $e) {

            }

            if (is_array($this->attributes['certificate_photo'])) {
                return join(',', $this->attributes['certificate_photo']);
            }

            return $this->attributes['certificate_photo'];
        }

        return null;
    }

    public function setCertificatePhotoAttribute($value) {
        if (!empty($value)) {
            $value = explode(',', $value);
            $value = json_encode($value);
        }

        $this->attributes['certificate_photo'] = $value;
    }



    public function getTeamPhotoAttribute() {
        if (isset($this->attributes['team_photo'])) {
            try {
                $this->attributes['team_photo'] = json_decode($this->attributes['team_photo']);
            }catch (\Exception $e) {

            }

            if (is_array($this->attributes['team_photo'])) {
                return join(',', $this->attributes['team_photo']);
            }

            return $this->attributes['team_photo'];
        }

        return null;
    }

    public function setTeamPhotoAttribute($value) {
        if (!empty($value)) {
            $value = explode(',', $value);
            $value = json_encode($value);
        }

        $this->attributes['team_photo'] = $value;
    }

    public function setAddressAttribute($value) {
        $addressId = $value['id'];
        $this->attributes['province_id'] = intval(substr($addressId, 0, 2).'0000');
        $this->attributes['province_name'] = $value['province'];
        $this->attributes['city_id'] = intval(substr($addressId, 0, 4).'00');
        $this->attributes['city_name'] = $value['city'];
        $this->attributes['county_id'] = intval($addressId);
        $this->attributes['county_name'] = $value['district'];
        $this->attributes['addr'] = isset($value['address']) ? $value['address'] : '';
    }

    public function getAddressAttribute() {
        if (!isset($this->attributes['county_id'])) {
            return null;
        }

        return [
            'id' => $this->attributes['county_id'],
            'province' => $this->attributes['province_name'],
            'city' => $this->attributes['city_name'],
            'district' => $this->attributes['county_name'],
            'address' => $this->attributes['addr'],
        ];
    }

//    public function getSubTeamCountAttribute() {
//        if (!isset($this->attributes['_lft']) || !isset($this->attributes['_rgt'])) {
//            return 0;
//        }
//
//        return floor(($this->attributes['_rgt'] - $this->attributes['_lft']) / 2);
//    }

    public function org() {
        return $this->belongsTo('App\Models\Org', 'org_id', 'id');
    }
    public function user() {
        return $this->belongsTo('App\User', 'user_id', 'id');
    }

    public function parentTeam() {
        return $this->belongsTo('App\Models\Team', 'parent_id', 'id');
    }

    public function syncServiceType() {
        if (!$this->id) {
            return false;
        }

        DB::table('team_service_category')->where('team_id', '=', $this->id)->delete();

        if ($this->type) {
            $inserts = [];

            foreach (explode(',', $this->type) as $item) {
                $inserts[] = [
                    'service_category_name' => $item,
                    'team_id' => $this->id,
                    'org_id'  => $this->org_id
                ];
            }

            DB::table('team_service_category')->insert($inserts);
        }
    }

    public function syncServiceTarget() {
        if (!$this->id) {
            return false;
        }

        DB::table('team_service_object')->where('team_id', '=', $this->id)->delete();

        if ($this->service_target) {
            $inserts = [];

            foreach (explode(',', $this->service_target) as $item) {
                $inserts[] = [
                    'service_object_name' => $item,
                    'team_id' => $this->id,
                    'org_id'  => $this->org_id
                ];
            }

            DB::table('team_service_object')->insert($inserts);
        }
    }

    public function plusTime($time) {
        if (!$this->id) {
            return false;
        }

        $this->fill([
            'reward_time' => $this->reward_time + $time
        ]);

        return $this->save();
    }

    public function syncTeamSize() {
        if (!$this->id) {
            return false;
        }
        $this->fill([
            'team_size' => UserTeam::where('team_id',  '=', $this->id)->where('verify_status', '=',  '1')->count()
        ]);
        return $this->save();
    }
}
